package tags.templates;

import java.text.SimpleDateFormat;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import main.PMF;
import main.UserView;

import DBClasses.Game;
import DBClasses.Game.PriceTypes;
import DBClasses.GameType;
import DBClasses.NewsLetter;
import DBClasses.User;

public class CatItemsTag extends TagSupport
{
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	public int doStartTag() throws JspException
	{
		String result = "";
		long id = (long) -1;
		boolean valid_gt = true;
		PersistenceManager manager = PMF.get().getPersistenceManager();
		List<GameType> gts = null;
		try
		{
			if (pageContext.getRequest().getParameter("id") != null
					&& pageContext.getRequest().getParameter("id") != "0")
			{
				id = Long
						.parseLong(pageContext.getRequest().getParameter("id"));
				gts = (List<GameType>) manager.newQuery(
						"select from " + GameType.class.getName()
								+ " where id == " + id).execute();
				if (gts == null || gts.size() <= 0)
				{
					result = "<div style=\"margin:20px\">Такой категории пока нет...</div>";
					valid_gt = false;
				}
			} else
				id = (long) 0;
		} catch (Exception ex)
		{
			result = "<div style=\"margin:20px\">Такой категории пока нет...</div>";
			valid_gt = false;
		}
		List<Game> gs = null;
		if (valid_gt)
		{			
			gs = (List<Game>) manager.newQuery(
					"select from " + Game.class.getName()).execute();
			String search="";
			if(pageContext.getRequest().getParameter("search") != null
					&&pageContext.getRequest().getParameter("search")!="")
			{
				search=pageContext.getRequest().getParameter("search").toLowerCase().trim();
			}
			if (gs != null && gs.size() > 0)
			{
				SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
				for (int i = 0; i < gs.size(); i++)
				{
					Game game = gs.get(i);
					if ((id == 0
							|| game.getGameType().equals(gts.get(0).getName()))&&game.getName().toLowerCase().trim().contains(search))
					{
						String cat = "0";
						gts = (List<GameType>) manager.newQuery(
								"select from " + GameType.class.getName()
										+ " where name == '"
										+ game.getGameType() + "'").execute();
						if (gts != null && gts.size() > 0)
							cat = gts.get(0).getId().toString();
						String lastres=result;
						String img_str="";
						if(game.getImg()!="")
							img_str="<img alt=\"\" src=\"/egs_img?max=300&img_id="
								+ game.getImg()
								+ "\" class=\"news_icon\"/>";
						result = "<div class=\"news_block\">"
								+ img_str
								+ "<div class=\"news_header\">"
								+ "<a href=\"/items.jsp?id="
								+ game.getId()
								+ "\">"
								+ game.getName()
								+ "</a>"
								+ "<div class=\"news_inf\">"
								+ sdf.format(game.getAddDate())
								+ ", "
								+ game.getAdder()
								+ "</div>"
								+ "<div class=\"news_inf\" style=\"color: #0099FF\">"
								+ "Жанр: <a class=\"cats_data\" href=\"/categories.jsp?id="
								+ cat
								+ "\">"
								+ game.getGameType()
								+ "</a>"
								+ "</div>"
								+ "<div class=\"cats_inf\">"
								+ "Цена: <a class=\"cats_data\">"
								+ game.getPrice(PriceTypes.Rubl)
								+ "</a>"
								+ "</div>"
								+ "<div class=\"cats_inf\" style=\" height:30px\">"
								+ "<a class=\"log_reg_btn top_text_stl\" id=\"buy_btn\" style=\"width:180px\" "
								+ "onclick=\"SubmitBuy('/buy?id="+
								+ game.getId()
								+ "');\">Добавить в корзину"
								+ "</a></div>"
								+ "</div>";
						
						UserView uv = (UserView) ((HttpServletRequest) pageContext.getRequest())
						.getSession().getAttribute("user");
						User usr = null;
						if (uv != null)
							usr = uv.getUser();
						if (usr != null && usr.haveShopAccess())
							result += "<input type=\"submit\" value=\"Удалить\" onclick=\"DeleteGame("
									+ game.getId() + ");\">";
						result+="</div>" + lastres;
					}
				}
			} else
			{
				result = "<div style=\"margin:20px\">Игр в такой категории пока нет...</div>";
			}
		}

		try
		{
			pageContext.getOut().flush();
			pageContext.getOut().print(result);
		} catch (Exception ex)
		{
			throw new JspException(ex.getMessage());
		}
		manager.close();
		return SKIP_BODY;
	}

	public void release()
	{
	}
}
